

import web3 from 'web3/dist/web3.min.js'
import UtilTool from '../../tools/UtilTool';
class login {
    web3: any;
    ethereum: any;
    rpc: any;
    constructor(web3,ethereum,rpc){
        this.web3 = web3;
        this.ethereum = ethereum;
        this.rpc = rpc;
    }
    getUserAccount = async () =>{
        //掉起钱包获取钱包地址
        const selectedAccount = await window.ethereum
        .request({
          method: "eth_requestAccounts",
        })
        .then((accounts: any[]) => accounts[0]);
        localStorage.setItem('userWalletAddress',selectedAccount)
        return selectedAccount;
    }
    connectNetwork = (chainIndex) =>{
      
        return new Promise(async (reslove,reject) =>{
            try {
                await this.ethereum.enable();
                let getChainId = await this.web3.eth.getChainId(); //通过web3.js 去 获取用户钱包当前的链
              
                UtilTool.printLog(getChainId,'====getChainId');
                if (getChainId === this.rpc[chainIndex].chainID) { //用户的链是不是我们要求的链  getChainId 用户当前的链 === this.rpc.chainID 我们的链
                  reslove(await this.getUserAccount());
                }else{
                  //下面代码是切换链
                  await (window.ethereum as any).request({
                    method: 'wallet_addEthereumChain',
                    params: [
                      {
                        chainId: this.web3.utils.numberToHex(this.rpc[chainIndex].chainID), // 目标链ID
                        chainName: this.rpc[chainIndex].chainName,
                        nativeCurrency: {
                          name: this.rpc[chainIndex].symbol,
                          symbol:  this.rpc[chainIndex].symbol,
                          decimals: 18
                        },
                        rpcUrls: [this.rpc[chainIndex].URL], // 节点
                        blockExplorerUrls: ['https://www.bscscan.com']
                      }
                    ]
                  }).then(async() =>{
                    reslove(await this.getUserAccount());
                  })
                }
                // let data =  await this.ethereum.request({
                //   method: 'wallet_switchEthereumChain',
                //   params: [{
                //     chainId: this.web3.utils.numberToHex(this.rpc[chainIndex].chainID) // 目标链ID
                //   }]
                // });
                // reslove(await this.getUserAccount());
              } catch (e) {
                UtilTool.printLog(e,'切换链报错');
                
                // if ((e as any).code === 4902) {
                //   try {
                //      await (window.ethereum as any).request({
                //         method: 'wallet_addEthereumChain',
                //         params: [
                //           {
                //             chainId: this.web3.utils.numberToHex(this.rpc[chainIndex].chainID), // 目标链ID
                //             chainName: this.rpc[chainIndex].chainName,
                //             nativeCurrency: {
                //               name: this.rpc[chainIndex].symbol,
                //               symbol:  this.rpc[chainIndex].symbol,
                //               decimals: 18
                //             },
                //             rpcUrls: [this.rpc[chainIndex].URL], // 节点
                //             blockExplorerUrls: ['https://www.bscscan.com']
                //           }
                //         ]
                //       }).then()
                      
                //   } catch (ee) {
                //     UtilTool.printLog(ee,'ee');
                    
                //     reslove('')
                //   }
                // } else if ((e as any).code === 4001) {
                //     reslove('')
                // } else if ((e as any).code === -32002) {
                //     reslove(await this.getUserAccount())
                // }
             }  
        } )
    }
    
}

// export default login
export const init = (rpc) =>{
    try {
      let ethereum = (window as any).ethereum;
      if (ethereum) {
        return new login(new web3(window.ethereum),ethereum,rpc);
      } else {
        alert("wallet not found");
      }
    } catch (err) {
        UtilTool.printLog(err,'web3登录失败，请检查代码');
    }
};